package tool

import (
	"fmt"
	log "github.com/Sirupsen/logrus"
	"github.com/go-xorm/xorm"
	_ "github.com/mattn/go-sqlite3"
)

var (
	engine *xorm.Engine
	dbPath = "/home/Laily/go/src/hj-check-in/the.db"
)

type Tasks struct {
	Name   string
	Param  string
	Stid   int
	User   int64
	Active int
}

type Users struct {
	Id     int64
	Name   string
	Email  string
	Url    string
	Active int
}

func init() {
	var err error
	engine, err = xorm.NewEngine("sqlite3", dbPath)
	if err != nil {
		fmt.Println("init db error: ", err)
	}
}

func GetTasks() []map[string][]byte {
	sql := "SELECT u.name, u.url, t.param, t.name AS stname, u.email, t.stid FROM users AS u,tasks AS t WHERE u.id = t.user AND u.active = 1 AND t.active = 1"
	results, err := engine.Query(sql)
	if err != nil {
		fmt.Println("res get error: ", err)
	}
	return results
}

func GetTaskByUserAndST(uid, stID int) []map[string][]byte {
	sql := "SELECT u.name, u.url, t.param, t.name AS stname, u.email, t.stid FROM users AS u,tasks AS t WHERE u.id = t.user AND u.active = 1 AND t.active = 1 AND u.id = %d AND t.stid = %d"
	sql = fmt.Sprintf(sql, uid, stID)
	results, err := engine.Query(sql)
	if err != nil {
		log.Error("res get error: ", err)
	}
	return results
}

func GetUser(id int64) *Users {
	user := &Users{Id: id}
	engine.Get(user)
	return user
}

func AddTask(userID int64, stname string, stid int) {
	t := &Tasks{User: userID, Name: stname, Stid: stid, Active: 1}
	_, err := engine.Insert(t)
	if err != nil {
		log.Println("insert task error: ", err)
	}
}

func AddUser(username string, url string, email string) int64 {
	u := &Users{Name: username, Url: url, Email: email, Active: 1}
	engine.Insert(u)
	return u.Id
}
